﻿using System;
using System.Collections.Generic;
using System.Net.Http;
using System.Threading.Tasks;
using IdentityModel.Client;
using Newtonsoft.Json.Linq;
using static IdentityModel.OidcConstants;
using Newtonsoft.Json;
namespace IdentityServerClient
{
    class Program
    {
        static async Task Main(string[] args)
        {
            Console.WriteLine("Hello IdentityServer4!");
            var client = new HttpClient();
            var disco = await client.GetDiscoveryDocumentAsync("http://localhost:22723");
            if (disco.IsError)
            {
                Console.WriteLine(disco.Error);
                return;
            }

            Dictionary<string, string> dict = new Dictionary<string, string>
            {
                ["client_id"] = "ResourceOwnerPasswordClientId",
                ["client_secret"] = "secret",
                ["grant_type"] = "password",
                ["username"] = "李锋",
                ["password"] = "123456"
            };

            HttpContent content = new FormUrlEncodedContent(dict);

            var tokenResponse = await client.PostAsync(disco.TokenEndpoint, content);

            string result = await tokenResponse.Content.ReadAsStringAsync();

            var tokenResult = JsonConvert.DeserializeObject<TokenResult>(result);
            Console.WriteLine(tokenResult.Access_token);
            //var client1 = new HttpClient();

            //client1.SetBearerToken(tokenResult.Access_token);
            //var response1 = await client1.GetAsync("http://localhost:5100/consul/Health");
            ////var response = await client1.GetAsync("http://localhost:22623/api/Identity/IdentityApi");
            //var response = await client1.GetAsync("http://localhost:5100/consul/Health/test");
            ////var response = await client1.GetAsync("http://localhost:5000/api/Health/test");
            
            //if (!response.IsSuccessStatusCode)
            //{
            //    Console.WriteLine(response.StatusCode);
            //}
            //else
            //{
            //    var contentStr = await response.Content.ReadAsStringAsync();
            //    Console.WriteLine(contentStr);
            //}
            //if (!response1.IsSuccessStatusCode)
            //{
            //    Console.WriteLine(response1.StatusCode);
            //}
            //else
            //{
            //    var contentStr = await response1.Content.ReadAsStringAsync();
            //    Console.WriteLine(contentStr);
            //}
            Console.ReadKey();
        }
    }
    public class TokenResult
    {
        public string Access_token { get; set; }
        public string Expires_in { get; set; }
        public string Token_type { get; set; }
        public string Refresh_token { get; set; }
    }
}
